<template>
  <div class="page-container">
    <div class="profile-header">
      <div class="profile-avatar">
        <el-avatar :size="100" :src="avatarUrl" />
      </div>
      <div class="profile-user-info">
        <h2 class="username">{{ userInfo.username }}</h2>
        <p class="registration-date">注册于: {{ userInfo.createdAt }}</p>
      </div>
       <el-button type="primary" class="edit-btn" @click="showEditDialog" round>
        <el-icon><Edit /></el-icon>编辑资料
      </el-button>
    </div>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-card class="info-card">
           <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon><span>关于我</span>
            </div>
          </template>
          <div class="info-item">
            <strong>用户名:</strong><span>{{ userInfo.username }}</span>
          </div>
           <div class="info-item">
            <strong>手机号:</strong><span>{{ userInfo.phone }}</span>
          </div>
          <div class="info-item">
            <strong>昵称:</strong><span>{{ userInfo.nickname }}</span>
          </div>
          <div class="info-item">
            <strong>创建时间:</strong><span>{{ userInfo.createdAt }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="change-password-card">
          <template #header>
            <div class="card-header">
              <el-icon><Lock /></el-icon><span>修改密码</span>
            </div>
          </template>
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPwd">
              <el-input
                v-model="passwordForm.oldPwd"
                type="password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPwd">
              <el-input
                v-model="passwordForm.newPwd"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="newPwd1">
              <el-input
                v-model="passwordForm.newPwd1"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="changePassword"
                :loading="submittingPassword"
              >
                <el-icon><Lock /></el-icon>确认修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="称呼" prop="phone">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit" :loading="submittingEdit">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, Lock, User } from '@element-plus/icons-vue'
import {findAllUsers, passwordsUpdate, UserUpdate} from "@/assets/user.js";
import {useUserStore} from "@/pinia/index.js";
var useUserStore1 = useUserStore();
const avatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
// 用户信息
const userInfo = reactive({
  username:"",
  phone:"",
  nickname:'',
  createdAt: ''
})
const findAllUser = (id) => {
  findAllUsers(useUserStore1.getUserId).then(res => {
    userInfo.username = res.data.data.username
    userInfo.phone = res.data.data.phone
    userInfo.nickname = res.data.data.nickname
    userInfo.createdAt = res.data.data.createdAt
  })
}
findAllUser(useUserStore1.getUserId);

// 编辑信息相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  username: '',
  phone: '',
  nickname:'',
  createdAt:''
})
const submittingEdit = ref(false)
const saveEdit = () =>{
  UserUpdate(useUserStore1.getUserId,editForm.username,editForm.phone,editForm.nickname).then(res=>{
    if(res.data.code ==200){
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      findAllUser(useUserStore1.getUserId);
      editDialogVisible.value=false
    }
  })
}

const editRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能小于2个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 修改密码相关
const submittingPassword = ref(false)

const passwordFormRef = ref(null)
const passwordForm = ref({
  oldPwd: '',
  newPwd: '',
  newPwd1: ''
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value !== passwordForm.value.newPwd) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const passwordRules = {
  oldPwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
  ],
  newPwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
  ],
  newPwd1: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
  ]
}

const changePassword = async () => {
  try {
    // 验证表单
    await passwordFormRef.value.validate()

    submittingPassword.value = true

    // 调用API修改密码
    const res = await passwordsUpdate(
        useUserStore1.getUserId,   // id
        passwordForm.value.oldPwd,  // oldPwd
        passwordForm.value.newPwd,  // newPwd
        passwordForm.value.newPwd1  // newPwd1
    )

    if (res.data.code === 200) {
      ElMessage.success('密码修改成功')
      passwordFormRef.value.resetFields() // 重置表单
    } else {
      ElMessage.error(res.data.message || '密码修改失败')
    }
  } catch (error) {
    if (error?.errors) {
      // 这是表单验证错误，不需要处理
      return
    }
    ElMessage.error('修改密码时发生错误')
    console.error('密码修改错误:', error)
  } finally {
    submittingPassword.value = false
  }
}

// 显示编辑对话框
const showEditDialog = () => {
  editFormRef.value?.resetFields()
  editForm.username = userInfo.username
  editForm.phone = userInfo.phone
  editForm.nickname = userInfo.nickname
  editForm.createdAt = userInfo.createdAt
  editDialogVisible.value = true
  console.log(editForm)
  console.log(userInfo)
}
</script>

<style scoped>
.page-container {
  padding: 0;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.profile-header {
  position: relative;
  height: 250px;
  background: linear-gradient(135deg, #409EFF 0%, #66B1FF 100%);
  padding: 32px;
  display: flex;
  align-items: center;
  color: #fff;
  margin-bottom: 24px;
}

.profile-avatar {
  margin-right: 24px;
  border: 4px solid rgba(255,255,255,0.5);
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.profile-user-info .username {
  font-size: 2.5rem;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.profile-user-info .registration-date {
  font-size: 1rem;
  opacity: 0.9;
  margin: 0;
}

.edit-btn {
  position: absolute;
  top: 32px;
  right: 32px;
}

.info-card, .change-password-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  border: none;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #303133;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 16px 0;
  font-size: 1rem;
  border-bottom: 1px solid #f0f0f0;
}
.info-item:last-child {
  border-bottom: none;
}
.info-item strong {
  color: #606266;
}
.info-item span {
  color: #303133;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 16px 24px;
  background-color: #f7f8fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 12px 12px 0 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}

.el-button .el-icon {
  margin-right: 4px;
}
</style> 